<?php

namespace Common\Middleware\Cache;

use Common\Context\TcpContext;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Redis\RedisFactory;
use Psr\Container\ContainerInterface;

class RedisContextMiddleware
{
    /**
     * @var ContainerInterface
     */
    protected ContainerInterface $container;

    /**
     * @var RedisFactory
     */
    protected RedisFactory $redisFactory;

    /**
     * @var StdoutLoggerInterface
     */
    protected StdoutLoggerInterface $logger;

    public function __construct(ContainerInterface $container, RedisFactory $redisFactory, StdoutLoggerInterface $logger)
    {
        $this->container = $container;
        $this->redisFactory = $redisFactory;
        $this->logger = $logger;
    }

    public function handle($frame, \Closure $next)
    {
        $fd = $frame->fd;
        $coId = TcpContext::getContext('coId');

        // 将协程 ID 存储到 Redis
        $redis = $this->redisFactory->get('default');
        $redis->set("fd:{$fd}", $coId);

        return $next($frame);
    }
}
